<template>
  <a-row :gutter="16">
    <a-col :span="4">
      <a-card style="width: 100%; height: 880px;">
        <div>
          选择时间维度
          <el-button-group>
            <el-button type="small" @click="changeToYear">年</el-button>
            <el-button type="small" @click="changeToMonth">月</el-button>
            <el-button type="small" @click="changeToDay">日</el-button>
          </el-button-group>
        </div>
        <el-date-picker v-model="formInline.selectedDate"
          :type="formInline.pickerType"
          placeholder="请选择日期"
          @change="handleDateChange">
        </el-date-picker>
        <br><br>
        <el-select v-model="changeUrl" placeholder="请选择能源类型">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <hr>
        <el-tree :data="data"
          :props="defaultProps"
          show-checkbox
          @check-change="handleCheckChange">
        </el-tree>
      </a-card>
    </a-col>
    <a-col :span="20">
      <a-card style="width: 100%; height: 880px;">
        <div style="width:100%; height:450px;">
          <div id="main" class="five"></div>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>
  
<script>
import { httpAction, getAction, postAction } from '@/api/manage'
import * as echarts from 'echarts';
export default {
    data() {
      return {
        chart: null,
        data: [],
        xData: ['0:00','1:00','2:00','3:00','4:00','5:00','6:00','7:00','8:00','9:00','10:00',
        '11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'],
        defaultProps: {
          children: 'children',
          label: 'label',
          nodeKey: 'label', // 设置node-key属性为label
        },
        formInline: {
          labels: [],
          selectedDate: new Date(),
          pickerType: 'date', // 初始化时间选择器类型为完整日期时间
        },
        isRequesting: false,
        seriesData:[{name: '用电量', data: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], type: 'bar', smooth: true}],
        options: [{
          value: '选项1',
          label: '电'
        }, {
          value: '选项2',
          label: '天然气'
        }, {
          value: '选项3',
          label: '水'
        }, {
          value: '选项4',
          label: 'LPG'
        }, {
          value: '选项5',
          label: '水蒸气'
        }],
        changeUrl: '选项1',
        url: {
          getTree: '/sys/sysDepart/getTree',
          getStatistics:'/consumptionElectricity/consumptionElectricity/select',
          getTracking: '/consumptionElectricity/consumptionElectricity/getTracking',
        },
      };
    },
    methods: {
      getTree(){
        this.data = [];
        getAction(this.url.getTree).then((res)=>{
          this.data = this.processData(res.result); // 调用处理数据的方法
          console.log(this.data);
        });
      },
      handleCheckChange(data, checked, indeterminate) {
        // 根据当前选中的标签，遍历获取所有下级标签
        const getSubLabels = (data) => {
          if (!this.formInline.labels.some(e => e.label === data.label)) {
            this.formInline.labels.push(data.label);
          }
          if (data.children && data.children.length > 0) {
            data.children.forEach(child => {
              getSubLabels(child);
            });
          }
        };
        const removeLabel = (data) => {
          this.formInline.labels = this.formInline.labels.filter(item => item !== data.label);
          this.seriesData = this.seriesData.filter(item => item.name !== data.label);
          if (data.children && data.children.length > 0) {
            data.children.forEach(child => {
              removeLabel(child);
            });
          }
        };
        
        if (checked) {
          getSubLabels(data);
        } else {
          removeLabel(data);  // 调用removeLabel函数来移除取消选中的标签
        }
        
        this.formInline.labels = [...new Set(this.formInline.labels)];
        console.log(this.formInline);
        if (this.isRequesting) {
          return;
        }
        // 设置请求状态为正在进行中
        this.isRequesting = true;
        this.seriesData = []; // 重置为一个空数组
        postAction(this.url.getTracking, this.formInline)
        .then((res) => {
          console.log(res);
          // 在请求成功后的处理逻辑
          if(res.result == null || res.result.length == 0 || res.result == ""){
            // 清空数据
            this.seriesData = [{name: '用电量', data: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], type: 'bar', smooth: true}];
            this.getzhu();
            return;
          }
          let seriesData = [];
          let i = 0;
          this.formInline.labels.forEach(label=>{
            let conData = [];
            if(res.result[0].length == 0 && res.result[1].length == 0 && res.result[2].length == 0){
              return;
            }
            res.result[0].forEach(e=>{
              if(label == e.dept){
                conData.push(e.consumption);
              }
            })
            res.result[1].forEach(e=>{
              if(label == e.product){
                conData.push(e.consumption);
              }
            })
            res.result[2].forEach(e=>{
              if(label == e.productionLine){
                conData.push(e.consumption);
              }
            })
            // console.log(conData);
            seriesData.push({
              type:'bar',
              name:label,
              data:conData,
              smooth: true,
            })
            // this.$set(this.seriesData,i,seriesData);
            // console.log(this.seriesData);
            // i++;
          })
          this.seriesData = seriesData;
          console.log(this.seriesData);
          setTimeout(() => {
            // this.chart.setOption({
            //   series: this.seriesData
            // });
            this.getzhu();
          }, 400)
          
        })
        .catch((error) => {
          console.error('请求失败：', error);
          // 处理请求失败的情况
        })
        .finally(() => {
          // 请求完成后，重置请求状态为已完成
          this.isRequesting = false;
        });
      },
      processData(data) {
        if (!data) {
          return []; // 返回一个空数组
        }
        let processedData = [];
        for (let item of data) {
          let processedItem = {
            label: item.label, // 使用部门名称作为 label
            children: this.processData(item.children) // 递归处理子部门
          };
          processedData.push(processedItem);
        }
        return processedData;
      },
      changeToYear() {
        this.formInline.pickerType = 'year'; // 切换时间选择器类型为年份
        this.xData = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
        this.getzhu();
      },
      changeToMonth() {
        this.formInline.pickerType = 'month'; // 切换时间选择器类型为年月
        this.getxData();
      },
      changeToDay() {
        this.formInline.pickerType = 'date'; // 切换时间选择器类型为完整日期
        this.xData = ['0:00','1:00','2:00','3:00','4:00','5:00','6:00','7:00','8:00','9:00','10:00',
        '11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'];
        this.getzhu();
      },
      handleDateChange(value) {
        // 处理日期变化的逻辑
        if(this.formInline.pickerType == 'month'){
          this.getxData();
        }
        postAction(this.url.getTracking, this.formInline)
        .then((res) => {
          console.log(res);
          // 在请求成功后的处理逻辑
        })
        .catch((error) => {
          console.error('请求失败：', error);
          // 处理请求失败的情况
        })
      },
      getxData() {
        let date = this.formInline.selectedDate;
        let month = date.getMonth() + 1;
        const daysInMonth = new Date(date.getFullYear(), month, 0).getDate();
        const xData = Array.from({ length: daysInMonth }, (_, index) => `${index + 1}日`);
        this.xData = xData;
        this.getzhu();
      },
      getzhu(){
        if(this.chart != null && this.chart != '' && this.chart != undefined){
          this.chart.dispose();
        }
        var chartDom = document.getElementById('main');
        this.chart = echarts.init(chartDom);
        var option;
        option = {
          title: {
            text: '耗电总览'
          },
          tooltip: {
            trigger: 'axis', // 触发类型，在饼形图中为item
          },
          legend: {
            data: this.formInline.labels,
          },
          toolbox: {
            feature: {
              dataView: {
                show: true,
                readOnly: false
              },
              magicType: {
                show: true,
                type: ['line', 'bar']
              },
              restore: {
                show: true
              },
              saveAsImage: {
                show: true
              }
            },
            padding: [0,15,0,0]
          },
          xAxis: {
            type: 'category',
            data: this.xData,
            axisLabel: {
              interval: 0 // 或者设置为其他间隔值
            }
          },
          yAxis: {
            type: 'value',
            name: 'kwh'
          },
          series: this.seriesData,
        };
        option && this.chart.setOption(option,true);
      },
    },
    created () {
      this.getTree();
      setTimeout(() => {
        
      }, 400)
    },
    mounted(){
      
      setTimeout(() => {
        this.getzhu();
      }, 1000)
    },
  };
</script>

<style>
 .five {
  width: 100%;
  height: 100%;
}
</style>